package model

import (
	"game-server/interfaces"
	"game-server/message"
	"log"

	"github.com/gorilla/websocket"
)

// 全局变量，在启动时被其他包注入
var GlobalClientManager interfaces.IClientManager
var GlobalRouter interfaces.IRouter

// Client 表示一个WebSocket客户端连接
type Client struct {
	ID       uint            // 用户ID
	Username string          // 用户名
	Conn     *websocket.Conn // WebSocket连接
	Send     chan []byte     // 发送消息的通道
}

// GetID 获取客户端ID
func (c *Client) GetID() uint {
	return c.ID
}

// GetUsername 获取用户名
func (c *Client) GetUsername() string {
	return c.Username
}

// GetConn 获取WebSocket连接
func (c *Client) GetConn() *websocket.Conn {
	return c.Conn
}

// SendMessage 发送消息
func (c *Client) SendMessage(msg []byte) error {
	c.Send <- msg
	return nil
}

// writePump 处理发送到客户端的消息
func (c *Client) WritePump() {
	defer c.Conn.Close()

	for {
		select {
		case msg, ok := <-c.Send:
			if !ok {
				// 通道已关闭
				c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}

			err := c.Conn.WriteMessage(websocket.BinaryMessage, msg)
			if err != nil {
				log.Printf("发送消息失败: %v", err)
				return
			}
		}
	}
}

// readPump 处理来自客户端的消息
func (c *Client) ReadPump() {
	defer func() {
		c.Conn.Close()
		GlobalClientManager.RemoveClient(c.ID)
		close(c.Send)
		log.Printf("用户 %s (ID: %d) 已断开连接", c.Username, c.ID)
	}()

	for {
		_, data, err := c.Conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				log.Printf("读取消息错误: %v", err)
			}
			break
		}

		// 解析消息
		msg, err := message.GlobalCoder.Decode(data)
		if err != nil {
			log.Printf("解析消息失败: %v", err)
			continue
		}

		// 使用全局路由器处理消息
		err = GlobalRouter.Handle(c, msg.GetMsgId(), msg)
		if err != nil {
			log.Printf("处理消息 %d 失败: %v", msg.GetMsgId(), err)
		}
	}
}
